package a.a.a.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import a.a.a.filesystem.ContestRepository;
import a.a.a.filesystem.GroupRepository;

@Controller
@RequestMapping("/groups")
public class GroupController {

	@Autowired
	private GroupRepository groupRepository;
	@Autowired
	private ContestRepository contestRepository;
	
	public GroupRepository getGroupRepository() {
		return groupRepository;
	}
	
	public void setGroupRepository(GroupRepository yearRepository) {
		this.groupRepository = yearRepository;
	}
	
	public ContestRepository getContestRepository() {
		return contestRepository;
	}
	
	public void setContestRepository(ContestRepository contestRepository) {
		this.contestRepository = contestRepository;
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String createGroup(HttpServletRequest request) {
		//System.out.println(model.containsAttribute("id00"));
		String name = request.getParameter("groupId");
		if (name != null) {
			name = name.trim();
		}
		groupRepository.createGroup(name);
		return "redirect:home";
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String navigateGroup(Model model, @PathVariable String id) {
		// navigate to folder {id} if exists
		// otherwise navigate to error page
		if (groupRepository.groupExists(id)) {
			model.addAttribute("groupId", id);
			List<String> contests = contestRepository.getContests(id);
			model.addAttribute("allContests", contests);
			return "pages/group";
		}
		return "denial/groupNotFound";
	}
}
